package com.ybkj.daijia.api.driver.v4;

import com.ybkj.daijia.serverUtils.SettingUtils;
import com.ybkj.daijia.api.driver.Error;
import com.ybkj.daijia.api.driver.transport.ResultTransport;
import com.ybkj.daijia.api.util.ErrorConstantV4;
import com.ybkj.daijia.common.Result;
import com.ybkj.daijia.server.event.model.ActivityCheckEvent;
import com.ybkj.daijia.server.event.model.freight.FreightOrderAcceptEvent;
import com.ybkj.daijia.server.event.model.freight.FreightOrderCreateEvent;
import com.ybkj.daijia.server.freight.Order;
import com.ybkj.daijia.server.mc.Passenger;
import com.ybkj.daijia.server.model.Company;
import com.ybkj.daijia.server.model.Driver;
import com.ybkj.daijia.server.model.DriverLogin;
import com.ybkj.daijia.server.reactor.ReactorVo;
import com.ybkj.daijia.server.sales.Activity.ActivityEvent;
import com.ybkj.daijia.server.service.AreaService;
import com.ybkj.daijia.server.service.CompanyService;
import com.ybkj.daijia.server.service.DriverLoginService;
import com.ybkj.daijia.server.service.DriverService;
import com.ybkj.daijia.server.service.FreightService;
import com.ybkj.daijia.server.service.MemberAccountService;
import com.ybkj.daijia.server.service.MemberService;
import java.util.Date;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.ApplicationEventMulticaster;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller("FreightProcessControllerV4")
@RequestMapping(value = "driver/api/rest/v4")
public class FreightProcessController {

    private static final Logger logger = LoggerFactory.getLogger(FreightProcessController.class);

    @Autowired
    private DriverService driverService;

    @Autowired
    private CompanyService companyService;

    @Autowired
    private AreaService areaService;

    @Autowired
    private MemberAccountService memberAccountService;

    @Autowired
    private MemberService memberService;

    @Autowired
    private DriverLoginService driverLoginService;

    @Autowired
    private SettingUtils settingUtils;

    @Autowired
    private ApplicationEventMulticaster applicationEventMulticaster;

    @Autowired
    private FreightService freightService;

    /**
     * 司机补单
     */
    @RequestMapping(value = "fillOrderFreight", method = RequestMethod.POST)
    public @ResponseBody
    ResultTransport fillOrderFreight(String employToken, String fromPlace, Double clientLongitude,
        Double clientLatitude, Long startTime, String passengerPhone, String appKey,
        @RequestParam(required = false, value = "memo") String memo,
        @RequestParam(required = false, value = "flitting") Boolean flitting,
        @RequestParam(required = false, value = "receipt") Boolean receipt,
        @RequestParam(required = false, value = "receivedPay") Boolean receivedPay,
        @RequestParam(required = false, value = "payMount") Double payMount,
        @RequestParam(required = false, value = "budgetPay") Double budgetPay,
        @RequestParam(required = false, value = "waypoint") String waypoint) {

        logger.debug(
            "fillOrderFreight employToken:{},fromPlace:{},budgetPay:{},clientLongitude:{},clientLatitude:{},passengerPhone:{},startTime:{}",
            employToken, fromPlace, budgetPay, clientLongitude, clientLatitude, passengerPhone,
            startTime);

        if (StringUtils.isBlank(employToken) || StringUtils.isBlank(fromPlace)
            || null == clientLongitude || null == clientLatitude ||
            StringUtils.isBlank(passengerPhone) || null == startTime) {
            return ResultTransport.getErrorBy(ErrorConstantV4.PARAM_ERROR);
        }

        DriverLogin driverLogin = driverLoginService.selectByToken(employToken);

        if (null == driverLogin) {
            return ResultTransport.getErrorBy(ErrorConstantV4.TOKEN_ERROR);
        }

        if (System.currentTimeMillis() >= driverLogin.getDeathDate().getTime()) {
            return ResultTransport.getErrorBy(ErrorConstantV4.TOKEN_TIME_ERROR);
        }

        Driver driver = driverService.findOne(driverLogin.getDriverId());

        if (null == driver) {
            return ResultTransport.getErrorBy(ErrorConstantV4.EMPLOY_NOT_EXISTS);
        }

        if (driver.getIsFreeze()) {
            return ResultTransport.getErrorBy(ErrorConstantV4.EMPLOY_IS_FREEZE_ERROR);
        }

        if (!driver.getStatus().equals(Driver.DRIVER_ONLINE)) {
            if (driver.getStatus().equals(Driver.DRIVER_OFFLINE)) {
                return ResultTransport.getErrorBy(
                    new Error(ErrorConstantV4.EMPLOY_STATUS_ERROR.getCode(), "您还没有上班，不能补单"));
            } else {
                return ResultTransport.getErrorBy(
                    new Error(ErrorConstantV4.EMPLOY_STATUS_ERROR.getCode(), "有未完成的工单，暂不能补单"));
            }
        }

        if (!driver.getDriverJobType().contains(Driver.DriverJobType.freight.toString())) {
            return ResultTransport.getErrorBy(ErrorConstantV4.ORDER_IS_FREIGHT_ERROR);
        }

        if (null == driver.getTruckId()) {
            return ResultTransport.getErrorBy(ErrorConstantV4.EMPLOY_HAS_NO_FREIGHTCAR);
        }

        try {
            Order order = new Order();

            order.setEmployId(driver.getId());
            order.setEmployName(driver.getName());
            order.setEmployCompanyId(driver.getCompanyId());
            order.setEmployNo(driver.getUsername());//工号
            order.setEmployPhone(driver.getPhone());
            order.setEmployPhoto(driver.getPhoto());
            order.setEmployScore(driver.getStarLevel());
            order.setChannelName(Order.ORDER_TYPE_BUDAN);
            order.setStartTime(new Date(startTime));
            order.setStatus(Order.ORDER_STATUS_NEW);
            order.setMemo(memo);
            order.setFlitting(flitting);
            order.setReceipt(receipt);
            order.setReceivedPay(receivedPay);
            order.setPayMount(payMount);
            order.setBudgetPay(budgetPay);
            Passenger passenger = memberService.findOnePassengerByPhone(passengerPhone);

            if (null == passenger) {
                Passenger newPassenger = new Passenger();
                newPassenger.setPhone(passengerPhone);
                newPassenger.setChannel_name(Passenger.PASSENGER_CHANNEL_BUDAN);
                newPassenger.setType(Passenger.TYPE_PASSENGER);
                newPassenger.setAllowOverdraw(false);
                newPassenger.setLongitude(clientLongitude);
                newPassenger.setLatitude(clientLatitude);
                newPassenger.setCompanyId(driver.getCompanyId());
                Company company = companyService.findOne(driver.getCompanyId());
                newPassenger.setCompanyName(
                    company == null ? driver.getCompanyName() : company.getAbbreviation());

                try {
                    Result<Passenger> createPersonal = memberService.createPersonal(newPassenger);
                    if (null != createPersonal.getResult()) {
                        passenger = createPersonal.getResult();
                    } else {
                        return ResultTransport.getErrorBy(ErrorConstantV4.PASSENGER_NOT_EXISTS);
                    }
                } catch (Exception e) {
                    return ResultTransport.getErrorBy(ErrorConstantV4.SERVER_ERROR);
                }
                ReactorVo rVo = new ReactorVo();
                rVo.setPassenger(passenger);
                rVo.setActivityEvent(ActivityEvent.newRegister);
                ActivityCheckEvent activityCheckEvent = new ActivityCheckEvent(rVo);
                applicationEventMulticaster.multicastEvent(activityCheckEvent);
            }
            order.setPassengerId(passenger.getId());
            order.setPassengerName(passenger.getName());
            order.setPassengerPhone(passenger.getPhone());

            Result<Order> result = freightService.createMore(order, waypoint);

            if (result.isSuccess()) {
                order = result.getResult();
                driverService
                    .updateStatusAndJobStatus(Driver.DRIVER_BUSY, Driver.DRIVER_JOBSTATUS_FREIGHT,
                        order.getEmployId());
                try {
                    FreightOrderCreateEvent freightOrderCreateEvent = new FreightOrderCreateEvent(
                        order);
                    applicationEventMulticaster.multicastEvent(freightOrderCreateEvent);
                } catch (Exception e) {
                    e.printStackTrace();
                    System.err.println("推送错误");
                }
                //同时触发接单事件
                try {
                    FreightOrderAcceptEvent freightOrderAcceptEvent = new FreightOrderAcceptEvent(
                        order, driver);
                    applicationEventMulticaster.multicastEvent(freightOrderAcceptEvent);
                } catch (Exception e) {
                    e.printStackTrace();
                    System.err.println("推送错误");
                }
                ResultTransport instance = ResultTransport.getErrorBy(ErrorConstantV4.SUCCESS);
                instance.setData(order.getId());
                return instance;
            } else {
                return ResultTransport.getErrorBy(ErrorConstantV4.SERVER_ERROR);
            }

        } catch (Exception e) {
            logger.error("api v4 driver fillOrderFreight error: {}", e);
            return ResultTransport.getErrorBy(ErrorConstantV4.SERVER_ERROR);
        }

    }


}